package cn.com.xinjinfu.pdoulcProduct.activity.login;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.util.EntityUtils;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.com.xinjinfu.pdoulcProduct.MainActivity;
import cn.com.xinjinfu.pdoulcProduct.activity.base.BaseActivity;
import cn.com.xinjinfu.pdoulcProduct.common.ConstantValues;
import cn.com.xinjinfu.pdoulcProduct.entity.ResultBean;
import cn.com.xinjinfu.pdoulcProduct.R;
import cn.com.xinjinfu.pdoulcProduct.engine.DataHandler;
import cn.com.xinjinfu.pdoulcProduct.manager.ActivityManager;
import cn.com.xinjinfu.pdoulcProduct.manager.L;
import cn.com.xinjinfu.pdoulcProduct.manager.TitleManager;
import cn.com.xinjinfu.pdoulcProduct.manager.ToastManager;
import cn.com.xinjinfu.pdoulcProduct.manager.UIManager;
import cn.com.xinjinfu.pdoulcProduct.utils.NewUtil;

/**
 * 验证手机号是否注册
 * Created by android-adt on 2016/1/14.
 */
public class CheckMobileActivity extends BaseActivity {
    private Dialog dg;
    private Button mLogin;
    private EditText mLoginName;
    private String mobile;
    private TextView tv_error_hint;
    private String sspwd;

    public void toast(String test) {
        Toast.makeText(this, test, Toast.LENGTH_SHORT).show();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 101:
                    //登录
                    ResultBean bean = (ResultBean) msg.obj;
                    if (bean != null) {
                        if (bean.getCode() == -1) {
                            if (bean.getStatus() == 0) {
                                //跳转到注册页
                                Intent intent = new Intent(CheckMobileActivity.this, RegisterActivity.class);
                                intent.putExtra("mobile", mobile);
                                startActivity(intent);
                            } else if (bean.getStatus() == 1) {
                                //跳转到登陆页
                                Intent intent = new Intent(CheckMobileActivity.this, LoginActivity.class);
                                intent.putExtra("mobile", mobile);
                                startActivity(intent);
                            }
                        } else {
                            toast(bean.getMsg());
                        }
                    }
                    break;
                case 1:
                    ToastManager.showShort(CheckMobileActivity.this, "请检查网络连接");
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_check_mobile);
        ActivityManager.getInstance().addActivity(this);
        TitleManager.showTitle(this, "登录", "");
        mLoginName = (EditText) findViewById(R.id.login_username_et);
        mLoginName.addTextChangedListener(mTextWatcher);
        Intent intent = getIntent();
        sspwd = intent.getStringExtra("sspwd");
        tv_error_hint = (TextView) findViewById(R.id.tv_error_hint);
        mLogin = (Button) findViewById(R.id.login_login_bt);
        mLogin.setEnabled(false);
        mLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isMobileNum(mobile)) {
                    loginRequest();
                } else {
                    tv_error_hint.setText("手机号有误，请重新输入!");
                }
            }
        });
    }


    @Override
    public void onBackPressed() {
        if (sspwd != null && sspwd.equals("SSPWD")){
            startActivity(new Intent(this, MainActivity.class));
        }else {
            Intent intent = new Intent();
            intent.putExtra("mIndex", ConstantValues.HOME_FRAGMENT_INDEX);
            setResult(ConstantValues.BACK_MAIN_RESULTCODE, intent);
        }
        this.finish();
    }


    public static boolean isMobileNum(String mobiles) {
        Pattern p = Pattern
//                .compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
                .compile("^((13[0-9])|(14[4,7])|(15[^4,\\D])|(17[0,6,7,8])|(18[0-9]))(\\d{8})$");
        Matcher m = p.matcher(mobiles);
        System.out.println(m.matches() + "---");
        return m.matches();
    }

    /**
     * 验证手机号 网络请求
     */
    private void loginRequest() {
        dg = UIManager.getLoadingDialog(this);
        dg.setCanceledOnTouchOutside(false);
        dg.show();
        final Map<String, String> parameters = DataHandler.getParameters("1409");
        parameters.put("mobile", mobile);
        new Thread() {
            public void run() {
                try {
                    HttpResponse res = NewUtil.getEntitySetCookie(DataHandler.getBuildUrl(parameters), null, NewUtil.TYPE_GET);
                    if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                        dg.dismiss();
                        String string = EntityUtils.toString(res.getEntity());
                        ResultBean resultBean = JSONObject.parseObject(string, ResultBean.class);
                        Message msg = new Message();
                        msg.what = 101;
                        msg.obj = resultBean;
                        handler.sendMessage(msg);
                    }else {
                        dg.dismiss();
                    }
                } catch (Exception e1) {
                    dg.dismiss();
                    handler.sendEmptyMessage(1);
                    e1.printStackTrace();

                }
            }
        }.start();
    }

    TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int arg1, int arg2,int arg3) {
        }

        @Override
        public void onTextChanged(CharSequence s, int arg1, int arg2,int arg3) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            mobile = mLoginName.getText().toString();
            tv_error_hint.setText("");
            if (TextUtils.isEmpty(mobile)) {
                mLogin.setEnabled(false);
                tv_error_hint.setText("");
            }else {
                mLogin.setEnabled(true);
            }
        }
    };

}
